package org.orbis.logging;

import java.io.IOException;
import java.nio.charset.Charset;
import org.orbis.constants.Constants;
import org.orbis.toolbox.ByteConverter;

public class DeleterLog extends BinaryBufferingLog{
	public static final byte HEAD_ID = Constants.DELETE_TYPE_ID;
	public static final byte HEAD_CONTENT = Constants.DELETE_TYPE_CONTENT;
	public static final byte HEAD_APPENDIX = Constants.DELETE_TYPE_APPENDIX;
	public static final byte HEAD_INTFLAG = Constants.DELETE_TYPE_INTFLAG;
	public static final byte HEAD_LONGFLAG = Constants.DELETE_TYPE_LONGFLAG;

	public DeleterLog(String directory, String logFile) throws IOException{
		super(directory, logFile);
	}

	public byte getNextType() throws IOException{
		return (byte)reliefStream.read();
	}

	public String reliefString() throws IOException{
		if(!isReliefMode) throw new IOException("Relief stream does not exist.");
		byte[] b = new byte[2];

		reliefStream.read(b);
		b = new byte[ByteConverter.byteToInt(b)];
		reliefStream.read(b);

		return new String(b, Charset.forName("UTF-8"));
	}
	
	public int reliefFlagType() throws IOException {
		if(!isReliefMode) throw new IOException("Relief stream does not exist.");
		byte[] b = new byte[2];

		reliefStream.read(b);

		return ByteConverter.byteToInt(b);
	}

	public long reliefLong() throws IOException{
		if(!isReliefMode) throw new IOException("Relief stream does not exist.");
		byte[] b = new byte[8];

		reliefStream.read(b);

		return ByteConverter.byteToLong(b);
	}

	public int reliefInt() throws IOException{
		if(!isReliefMode) throw new IOException("Relief stream does not exist.");
		byte[] b = new byte[4];

		reliefStream.read(b);

		return ByteConverter.byteToInt(b);
	}

	public void logContent(String content) throws IOException{
		if(isReliefMode) return;

		inputStream.write(HEAD_CONTENT);
		byte[] b = content.getBytes(Charset.forName("UTF-8"));
		inputStream.write(ByteConverter.intToByte(b.length, 2));
		inputStream.write(b);
	}

	public void logAppendix(String appendix) throws IOException{
		if(isReliefMode) return;

		inputStream.write(HEAD_APPENDIX);
		byte[] b = appendix.getBytes(Charset.forName("UTF-8"));
		inputStream.write(ByteConverter.intToByte(b.length, 2));
		inputStream.write(b);
	}

	public void logID(long ID) throws IOException{
		if(isReliefMode) return;

		inputStream.write(HEAD_ID);
		byte[] b = ByteConverter.longToByte(ID, 8);
		inputStream.write(b);
	}

	public void logIntFlag(int type, int flagValue) throws IOException{
		if(isReliefMode) return;

		inputStream.write(HEAD_INTFLAG);
		byte[] b = ByteConverter.longToByte(type, 2);
		inputStream.write(b);
		b = ByteConverter.longToByte(flagValue, 4);
		inputStream.write(b);
	}

	public void logLongFlag(int type, long flagValue) throws IOException{
		if(isReliefMode) return;

		inputStream.write(HEAD_LONGFLAG);
		byte[] b = ByteConverter.longToByte(type, 2);
		inputStream.write(b);
		b = ByteConverter.longToByte(flagValue, 8);
		inputStream.write(b);
	}
}
